/*
 * lowPassFilter.c
 *
 *  Created: 20250319
 *  Author: Hecate
 */
#include "lowPassFilter.h"

#include <math.h>
#include <stdlib.h>

struct LowPassFilterData
{
    float alpha;
    float lastOutput;
    float filteredValue;
    uint8_t firstFlag;
};

LowPassFilterData *lowPassFilterInit(float alpha)
{
    LowPassFilterData *obj = (LowPassFilterData *) malloc(sizeof(LowPassFilterData));

    obj->alpha = alpha;

    obj->filteredValue = 0;
    obj->firstFlag = 1;
    obj->lastOutput = 0;

    return obj;
}

void lowPassFilter(LowPassFilterData *obj, float value)
{
    if (obj->firstFlag == 1)
    {
        obj->firstFlag = 0;
        obj->lastOutput = value;
    }

    obj->filteredValue = obj->alpha * value + (1.0f - obj->alpha) * obj->lastOutput;
    obj->lastOutput = obj->filteredValue;
}

float lowPassFilterGetValue(const LowPassFilterData *obj)
{
    return obj->filteredValue;
}
